﻿using UnityEngine;
using System.Collections;

public class pingpong : MonoBehaviour
{
	
	GameObject main, xq, cup, t1;
	Ray ray;
	RaycastHit hit;
	float f_1_x, f_2_x, f_1_y, f_2_y, f1, f2, Distance;
	bool cup_isexist = false;

	//public static int Score = 0;

	// Use this for initialization
	void Start ()
	{
		main = GameObject.Find ("Camera");
		xq = GameObject.Find ("Sphere");
		cup = GameObject.Find ("cup");
		t1 = GameObject.Find ("ts_t");
	}
	
	// Update is called once per frame
	void Update ()
	{
		Distance = Vector3.Distance (main.transform.position, cup.transform.position);


		if (cup_isexist == false) {
			t1.transform.GetComponent<TextMesh> ().text = "请对准标识";
		} else if (Distance < 6 && Distance > 0 && cup_isexist == true) {
			t1.transform.GetComponent<TextMesh> ().text = "距离杯子太近";
		} else if (Distance <= 28 && 6 <= Distance && cup_isexist == true) {
			t1.transform.GetComponent<TextMesh> ().text = "";
			ray = Camera.main.ScreenPointToRay (Input.mousePosition);
			if (Physics.Raycast (ray, out hit)) {
				if (hit.transform.name.ToString () == "Cube1") {

					Debug.DrawLine (ray.origin, hit.point);
					if (Input.GetKeyDown (KeyCode.Mouse0)) {
						f_1_x = hit.point.x;

						f_1_y = hit.point.y;

					}

					if (Input.GetKeyUp (KeyCode.Mouse0)) {
						f_2_x = hit.point.x;
						f_2_y = hit.point.y;
						f1 = f_2_y - f_1_y;
						//print (f1);

				
						GameObject Sphere = (GameObject)Instantiate (Resources.Load ("Sphere"), Camera.main.transform.position - new Vector3 (0, 1, 0), Camera.main.transform.rotation);

						Sphere.transform.parent = cup.transform;

						if (f1 < 0.08f) {
							f1 = 0.08f;
							Sphere.transform.GetComponent<Rigidbody> ().AddRelativeForce (new Vector3 (0, 660 * f1, 660 * f1));
 
						} else {
							Sphere.transform.GetComponent<Rigidbody> ().AddRelativeForce (new Vector3 (0, 660 * f1, 660 * f1));
						}
					}
				}
			}
		} else if (Distance > 28 && cup_isexist == true) {
			t1.transform.GetComponent<TextMesh> ().text = "距离杯子太远";
		}

	}


	void cupOnBecameVisible ()
	{
		cup_isexist = true;
	}

	void cupOnBecameInVisible ()
	{
		cup_isexist = false;
	}
}
